package Controller;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import entity.UserInfo;
import entity.Winner;
import java.awt.event.ActionEvent;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import model.UserInfoFacade;
import javax.faces.model.ListDataModel;
import org.primefaces.model.SelectableDataModel;

/**
 *
 * @author VietTien
 */
@ManagedBean
@RequestScoped
public class UserController {
    private String newUserId;
    private String newPassword;
    private String newPasswordConfirm;
    private Boolean newGender;
    private String newUsername;
    private String newEmail;
    private Date newBirthday;
    private String newPhoneNumber;
    private String newAddressInfo;

    public String getNewPassword() {
        return newPassword;
    }

    public String getNewUserId() {
        return newUserId;
    }

    public void setNewUserId(String newUserId) {
        this.newUserId = newUserId;
    }

    
    public void setNewPassword(String newPassword) {
        this.newPassword = newPassword;
    }

    public String getNewPasswordConfirm() {
        return newPasswordConfirm;
    }

    public void setNewPasswordConfirm(String newPasswordConfirm) {
        this.newPasswordConfirm = newPasswordConfirm;
    }

    public String getNewUsername() {
        return newUsername;
    }

    public void setNewUsername(String newUsername) {
        this.newUsername = newUsername;
    }

    public Date getNewBirthday() {
        return newBirthday;
    }

    public void setNewBirthday(Date newBirthday) {
        this.newBirthday = newBirthday;
    }

    public String getNewPhoneNumber() {
        return newPhoneNumber;
    }

    public void setNewPhoneNumber(String newPhoneNumber) {
        this.newPhoneNumber = newPhoneNumber;
    }

    public String getNewAddressInfo() {
        return newAddressInfo;
    }

    public void setNewAddressInfo(String newAddressInfo) {
        this.newAddressInfo = newAddressInfo;
    }

    public Boolean getNewGender() {
        return newGender;
    }

    public void setNewGender(Boolean newGender) {
        this.newGender = newGender;
    }

    public String getNewEmail() {
        return newEmail;
    }

    public void setNewEmail(String newEmail) {
        this.newEmail = newEmail;
    }
    
    
    
    private UserInfo current;
    private UserInfo user;
    private Object editObj;

    private DataModel items = null;
    private String oldPass, newPass, newPassConfirm;
    private String username, password, role;
    private String userfname, email, address, phone,email2;
    private Boolean gender;
    private Date birthday;
    private UserInfo selectuser;
    private List<UserInfo> userinfo;
    @EJB
    private UserInfoFacade userInfoFacade;
    private int selectedItemIndex;
    private Date minDobDate, maxDobDate;

 

    /** Creates a new instance of UserController */
    public UserController() {
        current = (UserInfo) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user");
        setDateRange();
    }

    public String getEmail2() {
        return email2;
    }

    public void setEmail2(String email2) {
        this.email2 = email2;
    }

    public Date getMaxDobDate() {
        return maxDobDate;
    }

    public void setMaxDobDate(Date maxDobDate) {
        this.maxDobDate = maxDobDate;
    }

    public Date getMinDobDate() {
        return minDobDate;
    }

    public void setMinDobDate(Date minDobDate) {
        this.minDobDate = minDobDate;
    }

    public String prepareView() {
        current = (UserInfo) getItems().getRowData();
        return "ViewUser";
    }

    public String prepareEdit() {

        current = (UserInfo) getItems().getRowData();
        return "EditEvent";
    }

    public UserInfo getselected() {
        if (current == null) {
            current = new UserInfo();
        }
        return current;
    }

    public UserInfo getSelectuser() {
        return selectuser;
    }

    public void setSelectuser(UserInfo selectuser) {
        this.selectuser = selectuser;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public Boolean getGender() {
        return gender;
    }

    public void setGender(Boolean gender) {
        this.gender = gender;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getUserfname() {
        return userfname;
    }

    public void setUserfname(String userfname) {
        this.userfname = userfname;
    }

    public UserInfo getCurrent() {
        return current;
    }

    public void setCurrent(UserInfo current) {
        this.current = current;
    }

    public Object getEditObj() {
        return editObj;
    }

    public void setEditObj(Object editObj) {
        this.editObj = editObj;
    }

    public String getNewPass() {
        return newPass;
    }

    public void setNewPass(String newPass) {
        this.newPass = newPass;
    }

    public String getNewPassConfirm() {
        return newPassConfirm;
    }

    public void setNewPassConfirm(String newPassConfirm) {
        this.newPassConfirm = newPassConfirm;
    }

    public String getOldPass() {
        return oldPass;
    }

    public void setOldPass(String oldPass) {
        this.oldPass = oldPass;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    public UserInfo getUser() {
        return user;
    }

    public void setUser(UserInfo user) {
        this.user = user;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    private UserInfoFacade getFacade() {
        return userInfoFacade;
    }

    public List<UserInfo> ShowAll() {
        return userInfoFacade.findAll();
    }

    public String checkLogin() {
        System.out.println("USERNAME : " + username);
        UserInfo newLogin =  userInfoFacade.checkLogin(username, password);
        if (newLogin == null) {
            JsfUtil.addErrorMessage("Invalid username or password!  ");
            return "login";
        } else {
            System.out.println("current username  : " + newLogin.getUserName());
            if ((newLogin != null)) {
                
                FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("user", newLogin);
                JsfUtil.addSuccessMessage("Welcome " + newLogin.getUserName());
                Date today = new Date();
                //check birthday
                if (newLogin.getBirthDay().getDate() == today.getDate()
                        && newLogin.getBirthDay().getMonth() == today.getMonth()) {
                    JsfUtil.addSuccessMessage(" Hi " + newLogin.getUserName() +  "  ! We  wish you a Happy birth today !  !");
                }
                return "home";
            } else {
                JsfUtil.addErrorMessage("This account has been disactive. Please contact Administrator for more information");
                return "login";
            }
        }
    }

    public String logout() {
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        return "home";
    }

    public void savePerson(ActionEvent actionEvent) {
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Welcome " + username + " " + userfname + "!"));
    }

    public String UserCreate() {
        try {
            current.setIsDelete(false);
            current.setIsAdmin(false);

            userInfoFacade.create(current);
            JsfUtil.addSuccessMessage("User was successfully created");
            return "/Admin/UserInfomation.xhtml";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, "A persistence error occurred.");
            return null;
        }
    }

    public String create() {
       
             if(userInfoFacade.CheckEmail(newEmail))
            {
                JsfUtil.addErrorMessage("Email already! Please choose other email !");
                return null;
            }
 
            if (JsfUtil.isSpacesOnly(newPassword.trim())) {
                JsfUtil.addErrorMessage("Please input Password field.");
                return null;
            }
             if (JsfUtil.isSpacesOnly(newPasswordConfirm.trim())) {
                JsfUtil.addErrorMessage("Please input Password  Confirm field.");
                return null;
            }
            
            if (JsfUtil.isSpacesOnly(current.getUserName().trim())) {
                JsfUtil.addErrorMessage("Please input Username field.");
                return null;
            }
            if (!newPassword.equals(newPasswordConfirm)) {
                             JsfUtil.addErrorMessage("Password Confirm must same as Password");
                return null;
            
             }
            this.newUserId = "User1";
            if (userInfoFacade.CheckUserID(newUserId) != null) {
                do { // khi ID trùng
                    String[] temp = userInfoFacade.CheckUserID(newUserId).split("r");
                    int j = Integer.parseInt(temp[1]);
                    newUserId = "User" + (j + 1);
                } while (userInfoFacade.CheckUserID(newUserId) != null);
            }


           UserInfo newUser = new UserInfo();
           newUser.setUserID(newUserId);
           newUser.setUserName(newUsername);
           newUser.setEmail(newEmail);
           newUser.setPhoneNumber(newPhoneNumber);
           newUser.setIsFullControl(false);
           newUser.setIsAdmin(false);
           newUser.setGender(newGender);
           newUser.setIsDelete(false);
           newUser.setUserPass(newPassword);
           newUser.setBirthDay(newBirthday);
           newUser.setAddressInfo(newAddressInfo);
           

            userInfoFacade.create(newUser);
            
            JsfUtil.addSuccessMessage("User was successfully created");
            return "/Admin/UserInfomation.xhtml";
            
        
    }

    public String update() {
       if (!JsfUtil.isSpacesOnly(email2.trim())) {
         if(userInfoFacade.CheckEmail(email2))
            {
                JsfUtil.addErrorMessage("Email already!");
                return null;
            }else{current.setEmail(email2);}
        }
            
            if (JsfUtil.isSpacesOnly(current.getUserName().trim())) {
                JsfUtil.addErrorMessage("Please input Username field.");
                return null;
            }
          
            userInfoFacade.edit(current);
            JsfUtil.addSuccessMessage("User was successfully updated");
            return "ViewUser";
        
    }

    public String updateProfile() {
        try {
            if (JsfUtil.isSpacesOnly(current.getUserName().trim())) {
                JsfUtil.addErrorMessage("Please input Username field.");
                return null;
            }else{
            userInfoFacade.edit(current);
            JsfUtil.addSuccessMessage("User was successfully updated");
            return "ViewProfile";
            }
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, "Error in update action !");
            return null;
        }
    }

    public String restore() {
        try {
            current = (UserInfo) getItems().getRowData();
            current.setIsDelete(false);
            userInfoFacade.edit(current);
            JsfUtil.addSuccessMessage("User was successfully active");
            reload();
            return "AdminListUser";
        } catch (Exception e) {
            System.out.println(e.toString());
            JsfUtil.addErrorMessage(e, "Error in delete action !");
            return null;
        }
    }

    public String delete() {
        try {
            current = (UserInfo) getItems().getRowData();
            current.setIsDelete(true);
            userInfoFacade.edit(current);
            JsfUtil.addSuccessMessage("User was successfully deactive");
            reload();
            return "AdminListUser";
        } catch (Exception e) {
            System.out.println(e.toString());
            JsfUtil.addErrorMessage(e, "Error in delete action !");
            return null;
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = new ListDataModel(userInfoFacade.listUser());
        }
        return items;
    }

    public void setItems(DataModel items) {
        this.items = items;
    }

    public UserInfo getSelected() {
            
          current.setAddressInfo("");
          
       
        return current;
    }

    public String prepareEditInView() {

        current = getSelected();
        return "EditUser";
    }

    public String prepareEditprofile() {
        current = getSelected();
        return "EditProfile";
    }

    public String cancelEditEvent() {
        reload();
        return "ViewUser";
    }

    public String cancelEditProfile() {
        reload();
        return "ViewProfile";
    }

    private void reload() {
        items = null;
    }

    public String addnewUser() {
        reload();
        return "UserSignup";
    }

    public String changePassword() {

            if (JsfUtil.isSpacesOnly(newPass.trim())) {
                JsfUtil.addErrorMessage("Please input pasword field.");
                return null;
            }
        if (oldPass.equals(current.getUserPass())) {
            current.setUserPass(newPass);
            userInfoFacade.edit(current);
            JsfUtil.addSuccessMessage("Change Password successful!!!");
            return "home";
        } else {
            JsfUtil.addErrorMessage("Old password error");
            return "ChangePassword";
        }


    }

    public String resetPass(ActionEvent evt) {
        //pattern of username: Staffxxxxxx | Studentxxxxxx
        //pattern of pass    : xxxxxx   _6 digits after Staff|Student
        String pass = "";
        if (user.getUserName().matches("^User[0-9]{6}$")) {
            pass = user.getUserName().substring(4);
        } else {
            pass = "123456";
        }
        System.out.println("NEW PASS: " + pass);
        user.setUserPass(pass);
        try {
            getFacade().edit(user);
            JsfUtil.addSuccessMessage("Reset Password Successful. New Password of User: " + user.getUserName() + " is " + user.getUserPass());
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
        return "home";
    }

    private void setDateRange() {

        Date current = new Date();
        minDobDate = new Date(current.getYear() - 60, 0, 1);
        maxDobDate = new Date(current.getYear() - 15, 11, 31);
    }

    public String backToHome() {
        return "UserSigupCancel";
    }
}
